import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class DNSRequestHandler extends Thread {
	private DNSDatabase database;
	private DatagramPacket message;

	public DNSRequestHandler(DNSDatabase database, DatagramPacket message) {
		this.database = database;
		this.message = message;
	}

	public void run() {

		try {
			// Ricostruisco il messaggio
			ObjectInputStream iStream = new ObjectInputStream(
					new ByteArrayInputStream(message.getData()));
			String request = (String) iStream.readObject();
			iStream.close();

			// Cerco la rispotsa
			DomainInfo info = database.searchDomain(request);

			// Invio la risposta
			boolean found = false;
			if (info != null)
				found = true;
			Message m = new Message(info, found);
			// Creo la socket dalla quale viene inviata la risposta.
			// Si è preferito utilizzare un'altra porta per le risposte in modo
			// da non occupare la porta di ricezione delle richiesto
			DatagramSocket responseSocket = new DatagramSocket();
			responseSocket.send(createDatagram(m, message.getAddress(),
					message.getPort()));
			responseSocket.close();

		} catch (ClassNotFoundException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private DatagramPacket createDatagram(Message m, InetAddress address,
			int port) throws IOException {
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		ObjectOutput oo = new ObjectOutputStream(bStream);
		oo.writeObject(m);
		oo.close();
		byte sendData[] = new byte[1024];
		sendData = bStream.toByteArray();
		bStream.close();

		DatagramPacket sendPacket = new DatagramPacket(sendData,
				sendData.length, address, port);
		return sendPacket;
	}
}
